//
//  LevelCompleteLayer.m
//  GameProject
//
//  Created by Blair Trusler on 01/12/2011.
//  Copyright (c) 2011 Blair Trusler. All rights reserved.
//

#import "GameHeader.h"

@implementation LevelCompleteLayer

-(id)init{
	self = [super init];
	if (self != nil) {
		// Accept touch input
		self.isTouchEnabled = YES;
        
        [AudioManager levelCompleteMusic];

        score = 0;
        [self returnScore];
        
        CCSprite *titleText = [CCSprite spriteWithFile:@"LevelComplete.png"];
        CCSprite *textBody = [CCSprite spriteWithFile:@"LevelCompleteFull.png"];
        
		CGSize screenSize = [CCDirector sharedDirector].winSize;
        
        
        NSString *timeTakenString = [NSString stringWithFormat:@"Time Taken: %d:%d",timeMinutes,timeSeconds];
        CCLabelTTF *timeTakenLabel = [CCLabelTTF labelWithString:timeTakenString fontName:@"Courier" fontSize:32];

        CCMenuItemImage *returnToMenuButton = [CCMenuItemImage itemFromNormalImage:@"ReturnToMenu.png" selectedImage:@"ReturnToMenu1.png" target:self selector:@selector(returnMenu:)];
        CCMenuItemImage *retryLevelButton = [CCMenuItemImage itemFromNormalImage:@"RetryLevel.png" selectedImage:@"RetryLevel1.png" target:self selector:@selector(retryLevel:)];

        CCMenu *returnMenu = [CCMenu menuWithItems:returnToMenuButton, nil];
        CCMenu *retryMenu =[CCMenu menuWithItems:retryLevelButton, nil];
        
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
            titleText.position = ccp(screenSize.width/2,700);
            textBody.position = ccp (500,500);
            [timeTakenLabel setPosition:ccp(500, 50)];
            
            returnMenu.position = ccp(500,300);
            retryMenu.position = ccp(500,150);

        }
        else{
            titleText.scale = 0.5f;
            textBody.scale = 0.5f;
            titleText.position=ccp(screenSize.width*0.5,screenSize.height*0.9);
            textBody.position=ccp(screenSize.width*0.5,screenSize.height*0.6);
            
            [timeTakenLabel setPosition:ccp(screenSize.width*0.5,20)];
            returnToMenuButton.scale = 0.5;
            retryLevelButton.scale = 0.5f;
            returnMenu.position = ccp(screenSize.width*0.5,screenSize.height*0.3);
            retryLevelButton.position = ccp(0,-100);
            
        }
        
        [self addChild:titleText];
        [self addChild:textBody];
        
		[self addChild:timeTakenLabel];
        [self addChild: returnMenu];
        [self addChild:retryMenu];
        [self rewardAchievements];
	}
	return self;
}

-(void)retryLevel:(id) sender{
    [AudioManager playMenuButtonClick];
    [[CCDirector sharedDirector] resume];
    if (levelPlayed==1){
        [[SceneManager sharedSceneManager] runSceneWithID:kGameLevel1];    
    }
    if (levelPlayed==2){
        [[SceneManager sharedSceneManager] runSceneWithID:kGameLevel2];    
    }
    if (levelPlayed==3){
        [[SceneManager sharedSceneManager] runSceneWithID:kGameLevel3];    
    }
    if (levelPlayed == 4){
        [[SceneManager sharedSceneManager] runSceneWithID:kGameLevel4];    
    }
    if (levelPlayed == 5){
        [[SceneManager sharedSceneManager] runSceneWithID:kGameLevel5];    
    }

}

-(void)returnMenu:(id) sender{
    [AudioManager playMenuButtonClick];
    [[CCDirector sharedDirector] resume];
    [[SceneManager sharedSceneManager] runSceneWithID:kMainMenuScene];    
}


-(void)rewardAchievements{
    if (levelPlayed == 1){
        //Award achievement if not had a battle before:
        if (![GameState sharedInstance].achievement1){
            [GameState sharedInstance].achievement1 = TRUE;
            [[GameState sharedInstance]save];
            [[GameCenterLogin sharedInstance] reportAchievement:kAchievement1 percentComplete:100.0];
//            NSString *achievementName = [NSString stringWithFormat:kAchievement1];
//            CCLOG(@"Awarded Achievement - %@",achievementName);
        }   
    }
    
    if (levelPlayed == 2){
        //Award achievement if not had a battle before:
        if (![GameState sharedInstance].achievement2){
            [GameState sharedInstance].achievement2 = TRUE;
            [[GameState sharedInstance]save];
            [[GameCenterLogin sharedInstance] reportAchievement:kAchievement2 percentComplete:100.0];
//            NSString *achievementName = [NSString stringWithFormat:kAchievement2];
//            CCLOG(@"Awarded Achievement - %@",achievementName);
        }   
    }
    
    if (levelPlayed == 3){
        //Award achievement if not had a battle before:
        if (![GameState sharedInstance].achievement3){
            [GameState sharedInstance].achievement3 = TRUE;
            [[GameState sharedInstance]save];
            [[GameCenterLogin sharedInstance] reportAchievement:kAchievement3 percentComplete:100.0];
//            NSString *achievementName = [NSString stringWithFormat:kAchievement3];
//            CCLOG(@"Awarded Achievement - %@",achievementName);
        }   
    }
}

    



-(void)returnScore{
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    // Get high scores array from "defaults" object
    NSMutableArray *highScores = [NSMutableArray arrayWithArray:[defaults arrayForKey:@"scores"]];
    NSMutableArray *highScores2 = [NSMutableArray arrayWithArray:[defaults arrayForKey:@"scores2"]];
    NSMutableArray *highScores3 = [NSMutableArray arrayWithArray:[defaults arrayForKey:@"scores3"]];
    NSMutableArray *highScores4 = [NSMutableArray arrayWithArray:[defaults arrayForKey:@"scores4"]];
    NSMutableArray *highScores5 = [NSMutableArray arrayWithArray:[defaults arrayForKey:@"scores5"]];

    int score1;

    
    if (levelPlayed == 1){
        //TODO: FIX        
        if (timeMinutes<1){
            if (timeSeconds<40){
                score = 3; //If completed in under 1 minute, reward 3 stars
                
                score1 = timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard1 score:(int)score1];
                
                if (![GameState sharedInstance].achievement4){
                    [GameState sharedInstance].achievement4 = TRUE;
                    [[GameState sharedInstance]save];
                    [[GameCenterLogin sharedInstance] reportAchievement:kAchievement4 percentComplete:100.0];
//                    NSString *achievementName = [NSString stringWithFormat:kAchievement4];
//                    CCLOG(@"Awarded Achievement - %@",achievementName);
                }

            }
            else{
                score = 2; //If completed in under 1 minute, reward 3 stars
                score1 = timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard1 score:(int)score1];

            }        
        }
        else if (timeMinutes>1){
            for (int i = 0;i<=timeMinutes;i++){
                score1 +=60;
            }
            score1 +=timeSeconds;
            [[GameCenterLogin sharedInstance] reportScore:kLeaderboard1 score:(int)score1];
            
            score = 1;      //If over 1 minute, 1 star
        }
        
        // Iterate thru high scores; see if current point value is higher than any of the stored values
        for (int i = 0; i < [highScores count]; i++)
        {
            if (score >= [[highScores objectAtIndex:i] intValue])
            {
                // Insert new high score, which pushes all others down
                [highScores insertObject:[NSNumber numberWithInt:score] atIndex:i];
                
                // Remove last score, so as to ensure only 5 entries in the high score array
                [highScores removeLastObject];
                
                // Re-save scores array to user defaults
                [defaults setObject:highScores forKey:@"scores"];
                
                [defaults synchronize];
                
                NSLog(@"Saved new high score of %i", score);
                
                // Bust out of the loop 
                break;
            }
        }
        
    }
    
    
    
    //TODO:
    if (levelPlayed == 2){
        if (timeMinutes<1){
            if (timeSeconds<45){
                score = 3; //If completed in under 1 minute, reward 3 stars
                
                score1 = timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard2 score:(int)score1];

                if (![GameState sharedInstance].achievement5){
                    [GameState sharedInstance].achievement5 = TRUE;
                    [[GameState sharedInstance]save];
                    [[GameCenterLogin sharedInstance] reportAchievement:kAchievement5 percentComplete:100.0];
//                    NSString *achievementName = [NSString stringWithFormat:kAchievement5];
//                    CCLOG(@"Awarded Achievement - %@",achievementName);
                }
            }
            else{
                score = 2;
                score1 = timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard2 score:(int)score1];
            }
        }
        else if (timeMinutes<2){
            if (timeSeconds<15){
                score = 2;
                for (int i = 0;i<=timeMinutes;i++){
                    score1 +=60;
                }
                score1 +=timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard2 score:(int)score1];

            }
            else if ((timeSeconds>=15)&&(timeSeconds<60)){
                score = 1;
                for (int i = 0;i<=timeMinutes;i++){
                    score1 +=60;
                }
                score1 +=timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard2 score:(int)score1];

            }
        }
        else if (timeMinutes>=2){
            score = 1;
            for (int i = 0;i<=timeMinutes;i++){
                score1 +=60;
            }
            score1 +=timeSeconds;
            [[GameCenterLogin sharedInstance] reportScore:kLeaderboard2 score:(int)score1];

        }

        for (int i = 0; i < [highScores2 count]; i++)
        {
            if (score >= [[highScores2 objectAtIndex:i] intValue])
            {
                // Insert new high score, which pushes all others down
                [highScores2 insertObject:[NSNumber numberWithInt:score] atIndex:i];
                
                // Remove last score, so as to ensure only 5 entries in the high score array
                [highScores2 removeLastObject];
                
                // Re-save scores array to user defaults
                [defaults setObject:highScores2 forKey:@"scores2"];
                
                [defaults synchronize];
                
                NSLog(@"Saved new high score of %i", score);
                
                // Bust out of the loop 
                break;
            }
        }

        
        
    }    
    
    if (levelPlayed == 3){
        if (timeMinutes<1){
            if (timeSeconds<45){
                score = 3; //If completed in under 1 minute, reward 3 stars
                score1 = timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard3 score:(int)score1];

                if (![GameState sharedInstance].achievement6){
                    [GameState sharedInstance].achievement6 = TRUE;
                    [[GameState sharedInstance]save];
                    [[GameCenterLogin sharedInstance] reportAchievement:kAchievement6 percentComplete:100.0];
                    //                    NSString *achievementName = [NSString stringWithFormat:kAchievement5];
                    //                    CCLOG(@"Awarded Achievement - %@",achievementName);
                }
            }
            else{
                score = 2;
                score1 = timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard3 score:(int)score1];

            }
        }
        else if (timeMinutes<2){
            if (timeSeconds<15){
                score = 2;
                for (int i = 0;i<=timeMinutes;i++){
                    score1 +=60;
                }
                score1 +=timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard3 score:(int)score1];

            }
            else if ((timeSeconds>=15)&&(timeSeconds<60)){
                score = 1;
                for (int i = 0;i<=timeMinutes;i++){
                    score1 +=60;
                }
                score1 +=timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard3 score:(int)score1];

            }
        }
        else if (timeMinutes>=2){
            score = 1;
            for (int i = 0;i<=timeMinutes;i++){
                score1 +=60;
            }
            score1 +=timeSeconds;
            [[GameCenterLogin sharedInstance] reportScore:kLeaderboard3 score:(int)score1];
            
        }
        
        
        for (int i = 0; i < [highScores3 count]; i++)
        {
            if (score >= [[highScores3 objectAtIndex:i] intValue])
            {
                // Insert new high score, which pushes all others down
                [highScores3 insertObject:[NSNumber numberWithInt:score] atIndex:i];
                
                // Remove last score, so as to ensure only 5 entries in the high score array
                [highScores3 removeLastObject];
                
                // Re-save scores array to user defaults
                [defaults setObject:highScores3 forKey:@"scores3"];
                
                [defaults synchronize];
                
                NSLog(@"Saved new high score of %i", score);
                
                // Bust out of the loop 
                break;
            }
        }

        
    }
    
    if (levelPlayed == 4){
        if (timeMinutes<1){
            if (timeSeconds<45){
                score = 3; //If completed in under 1 minute, reward 3 stars
                score1 = timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard4 score:(int)score1];

            }
            else{
                score = 2;
                score1 = timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard4 score:(int)score1];

            }
        }
        else if (timeMinutes<2){
            if (timeSeconds<15){
                score = 2;
                for (int i = 0;i<=timeMinutes;i++){
                    score1 +=60;
                }
                score1 +=timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard4 score:(int)score1];

            }
            else if ((timeSeconds>=15)&&(timeSeconds<60)){
                score = 1;
                for (int i = 0;i<=timeMinutes;i++){
                    score1 +=60;
                }
                score1 +=timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard4 score:(int)score1];

            }
        }
        else if (timeMinutes>=2){
            score = 1;
            for (int i = 0;i<=timeMinutes;i++){
                score1 +=60;
            }
            score1 +=timeSeconds;
            [[GameCenterLogin sharedInstance] reportScore:kLeaderboard4 score:(int)score1];

        }
        
        
        for (int i = 0; i < [highScores4 count]; i++)
        {
            if (score >= [[highScores4 objectAtIndex:i] intValue])
            {
                // Insert new high score, which pushes all others down
                [highScores4 insertObject:[NSNumber numberWithInt:score] atIndex:i];
                
                // Remove last score, so as to ensure only 5 entries in the high score array
                [highScores4 removeLastObject];
                
                // Re-save scores array to user defaults
                [defaults setObject:highScores4 forKey:@"scores4"];
                
                [defaults synchronize];
                
                NSLog(@"Saved new high score of %i", score);
                
                // Bust out of the loop 
                break;
            }
        }
        
    }
    
    if (levelPlayed == 5){
        if (timeMinutes<1){
            if (timeSeconds<45){
                score = 3; //If completed in under 1 minute, reward 3 stars
                score1 = timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard5 score:(int)score1];

            }
            else{
                score = 2;
                score1 = timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard5 score:(int)score1];

            }
        }
        else if (timeMinutes<2){
            if (timeSeconds<15){
                score = 2;
                for (int i = 0;i<=timeMinutes;i++){
                    score1 +=60;
                }
                score1 +=timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard5 score:(int)score1];

            }
            else if ((timeSeconds>=15)&&(timeSeconds<60)){
                score = 1;
                for (int i = 0;i<=timeMinutes;i++){
                    score1 +=60;
                }
                score1 +=timeSeconds;
                [[GameCenterLogin sharedInstance] reportScore:kLeaderboard5 score:(int)score1];


            }
        }
        else if (timeMinutes>=2){
            score = 1;
            for (int i = 0;i<=timeMinutes;i++){
                score1 +=60;
            }
            score1 +=timeSeconds;
            [[GameCenterLogin sharedInstance] reportScore:kLeaderboard5 score:(int)score1];

        }
        
        
        for (int i = 0; i < [highScores5 count]; i++)
        {
            if (score >= [[highScores5 objectAtIndex:i] intValue])
            {
                // Insert new high score, which pushes all others down
                [highScores5 insertObject:[NSNumber numberWithInt:score] atIndex:i];
                
                // Remove last score, so as to ensure only 5 entries in the high score array
                [highScores5 removeLastObject];
                
                // Re-save scores array to user defaults
                [defaults setObject:highScores5 forKey:@"scores5"];
                
                [defaults synchronize];
                
                NSLog(@"Saved new high score of %i", score);
                
                // Bust out of the loop 
                break;
            }
        }
        
    }

    
}

@end
